package dev.tools.exchange;

import dev.tools.DevToolsAgent;
import io.netty.util.internal.StringUtil;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.Router;

public class Server {

    private int port;

    public Server(int port) {
        this.port = port;
    }

    public void startHttpServer() {
        Vertx vertx = Vertx.vertx();
        final Router router = Router.router(Vertx.vertx());

        router.route(HttpMethod.POST, "/source").handler(ctx -> {
            try {
                String code = ctx.request().getParam("code");
                if (StringUtil.isNullOrEmpty(code)) {
                    ctx.fail(new IllegalArgumentException("code is empty!!"));
                }
                DevToolsAgent.redefine(code);
                ctx.response().end("OK");
            } catch (Exception e) {
                ctx.fail(e);
            }
        });
        vertx.createHttpServer().requestHandler(router).listen(port);
    }
}